package cn.wolfcode.crm.service.imp;

import cn.wolfcode.crm.domain.RechargeServiceItem;
import cn.wolfcode.crm.mapper.RechargeServiceItemMapper;
import cn.wolfcode.crm.query.RechargeServiceItemQueryObject;
import cn.wolfcode.crm.service.IRechargeServiceItemService;
import cn.wolfcode.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class RechargeServiceItemServiceImpl implements IRechargeServiceItemService {
    @Autowired
    private RechargeServiceItemMapper rechargeServiceItemMapper;


    public void delete(Long id) {
        rechargeServiceItemMapper.deleteByPrimaryKey(id);
    }

    public RechargeServiceItem selectByPrimaryKey(Long id) {
        return rechargeServiceItemMapper.selectByPrimaryKey(id);
    }

    public List<RechargeServiceItem> selectAll() {
        return rechargeServiceItemMapper.selectAll();
    }

    public List<RechargeServiceItem> query(RechargeServiceItemQueryObject qo) {
        return rechargeServiceItemMapper.queryForList(qo);
    }

    public void recharge(RechargeServiceItem rechargeServiceItem) {
        /*保存自己*/
        //充值后的次数
        Integer beforeCount = rechargeServiceItem.getBeforeCount();
        Integer sum = Integer.sum(rechargeServiceItem.getCounts(), beforeCount);
        rechargeServiceItem.setAfterCount(sum);
        //操作时间
        rechargeServiceItem.setOpTime(new Date());
        //操作人员
        rechargeServiceItem.setOpUser(UserContext.getCurrentUser());
        rechargeServiceItemMapper.insert(rechargeServiceItem);
        /*保存中间记录数据(关联中间表),要分存不存在(存在update,不存在insert)*/
        Long clientId = rechargeServiceItem.getClient().getId();
        String serviceName = rechargeServiceItem.getServiceName();
        Integer count = rechargeServiceItemMapper.getBeforeCount(clientId, serviceName);
        if(count == null){
            rechargeServiceItemMapper.insertRelation(clientId,serviceName,sum);
        }else{
            rechargeServiceItemMapper.updateRelation(clientId,serviceName,sum);
        }

    }

    public List<Map<String,Object>> getService(Long clientId) {
        return rechargeServiceItemMapper.getService(clientId);
    }

    public Integer getBeforeCount(Long clientId, String serviceName) {
        return rechargeServiceItemMapper.getBeforeCount(clientId,serviceName);
    }
}
